package com.jacobson.huobi.mvp.fragment

import android.animation.ValueAnimator
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.jacobson.core.base.FragmentImmersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.widget.adapter.ListRecyclerAdapter
import com.jacobson.core.widget.storage.GlobalStorage
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.common.BaseSelectableFragment
import com.jacobson.huobi.common.constants.CommonConstant
import com.jacobson.huobi.common.constants.UserTypeConstant
import com.jacobson.huobi.components.SpaceItemDecoration
import com.jacobson.huobi.components.toptab.TabsData
import com.jacobson.huobi.di.components.DaggerSymbolFragmentComponent
import com.jacobson.huobi.di.modules.SymbolFragmentModule
import com.jacobson.huobi.entities.SymbolInfo
import com.jacobson.huobi.entities.SystemActiveInfo
import com.jacobson.huobi.entities.events.SystemActiveEvent
import com.jacobson.huobi.entities.events.UpdateEvent
import com.jacobson.huobi.entities.websocket.RefreshSymbolResp
import com.jacobson.huobi.mvp.KycAuthActivity
import com.jacobson.huobi.mvp.RenevalMemberActivity
import com.jacobson.huobi.mvp.adapters.SymbolAdapter
import com.jacobson.huobi.mvp.contract.SymbolContract
import com.jacobson.huobi.threads.TokenThread.loginRespVo
import com.jacobson.huobi.utils.ComparableHelper
import com.jacobson.huobi.utils.PreferencesUtil
import com.jacobson.huobi.utils.SettingProperties
import com.jacobson.huobi.utils.TokenStorageUtil
import com.jacobson.huobi.websocket.ProtocolFactory
import com.jacobson.huobi.websocket.WebsocketManager
import kotlinx.android.synthetic.main.fragment_currency.*
import kotlinx.android.synthetic.main.item_db_header.*
import org.simple.eventbus.Subscriber
import javax.inject.Inject

@FragmentImmersive
class SymbolFragment : BaseSelectableFragment<SymbolContract.Presenter>(),
    SymbolContract.View {

    @field:Inject
    lateinit var tabsData: TabsData
    @field:Inject
    lateinit var symbolAdapter: SymbolAdapter
    @field:Inject
    lateinit var symbolList: MutableList<SymbolInfo>
    private var animator: ValueAnimator? = null
    private var isSelected = false
    private var filterFavorite = false
    private var filterAnalysis = false
    private val handler = Handler(Looper.getMainLooper())
    private var hadInjected = false

    private var type: Int = 0

    private var keyword: String? = null
    private val finishSmartRefreshRunnable = Runnable {
        smartRefreshLayout.finishRefresh(false)
    }

    override fun setupFragmentComponent(appComponent: AppComponent) {
        DaggerSymbolFragmentComponent.builder()
            .appComponent(appComponent)
            .symbolFragmentModule(SymbolFragmentModule(this))
            .activityModule(ActivityModule(activity!!))
            .build()
            .inject(this)
        hadInjected = true
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.fragment_currency
    override fun initData(savedInstanceState: Bundle?) {
        arguments?.let {
            type = it.getInt(KEY_TYPE)
        }
        if (type == HUOBI) {
            // 第一个Fragment Immersive适配
            commonHeader.setForcePadding(true)
        }
        logger.d("SymbolFragment >>> $type >>> $symbolAdapter")
        update2Position(DEFAULT_POSITION)
        topTabContainer.setTabs(tabsData, DEFAULT_POSITION)
        topTabContainer.setOnItemSelectedListener { position, _ ->
            update2Position(position)
            when (position) {
                0 -> GlobalStorage.put(CommonConstant.KEY_SEL_VOLUME_LEVEL, "-1")
                4 -> GlobalStorage.put(CommonConstant.KEY_SEL_VOLUME_LEVEL, "-2")
                else -> GlobalStorage.put(CommonConstant.KEY_SEL_VOLUME_LEVEL, position)
            }

            WebsocketManager.sendMessage(ProtocolFactory.ofSubscribe())

        }
        smartRefreshLayout.setEnableLoadMore(false)
        smartRefreshLayout.setOnRefreshListener {
            presenter.updateSymbolList(getMarketName())
            handler.postDelayed(finishSmartRefreshRunnable, 5000)
        }
        rl_GoTo_RenevalMember.setOnClickListener(){
            if(tv_goto_vip_or_kyc.text.equals("续费解锁")){
                RenevalMemberActivity.startActivity(this.context!!)
            }
            else if(tv_goto_vip_or_kyc.text.equals("实名认证解锁")){
                KycAuthActivity.startActivity(this.context!!)
            }
        }

        symbolAdapter.setOnItemClickListener(object :
            ListRecyclerAdapter.OnItemClickListener<SymbolInfo> {
            override fun onItemClick(dataList: List<SymbolInfo>, data: SymbolInfo, position: Int) {
                symbolAdapter.setExpandPosition(position)
            }
        })
        with(recyclerView) {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(3f))
            adapter = symbolAdapter
        }

        if (loginRespVo != null && UserTypeConstant.isAdmin(loginRespVo!!.vipLevel)) {
            tv_goto_vip_or_kyc.text="续费解锁"
        }

        if( PreferencesUtil.getValue("isAlreadyKycAuth",false)==true){
            if( loginRespVo!!.vipLevel==0||loginRespVo!!.vipLevel==6||loginRespVo!!.vipLevel==5||loginRespVo!!.vipLevel==4||loginRespVo!!.vipLevel==3){
                rl_GoTo_RenevalMember.visibility = View.GONE
            }else{
                tv_goto_vip_or_kyc.text="续费解锁"
            }
        }else{
            tv_goto_vip_or_kyc.text="实名认证解锁"
        }


    }

    private fun update2Position(position: Int) {
        filterFavorite = position == 0
        filterAnalysis = position == 4
        updateShowDataList()
    }

    @Subscriber
    private fun onUpdate(updateEvent: UpdateEvent) {
        symbolList = GlobalStorage.get(Constants.KEY_SYMBOL_LIST) as MutableList<SymbolInfo>
        if (updateEvent.type == 2) {
            var alarmlist =
                GlobalStorage.get(CommonConstant.KEY_ALARM_SYMBOL_LIST) as MutableList<SymbolInfo>
            topTabContainer?.notifyNumberAlarm(alarmlist.filter { it.market == getMarketName() })
        }
        if (updateEvent.useKeyword) {
            keyword = updateEvent.keyword
        }
        updateShowDataList()
    }

    @Subscriber
    private fun onSystemActiveChanged(systemActiveEvent: SystemActiveEvent) {
        activity?.runOnUiThread {
            commonHeader.updateSystemStatus(GlobalStorage.get(Constants.KEY_SYSTEM_STATUS) as List<SystemActiveInfo>)
        }
    }

    @Subscriber
    private fun onRefreshSymbolResp(refreshSymbolResp: RefreshSymbolResp) {
        activity?.runOnUiThread {
            handler.removeCallbacks(finishSmartRefreshRunnable)
            smartRefreshLayout?.finishRefresh()
        }
    }

    private fun updateShowDataList() {
        var realTimeAllCount = 0;
        for (symbolInfo in symbolList) {
            if (symbolInfo.market == getMarketName() && symbolInfo.realtimePrimary) {
                realTimeAllCount++;
            }
        }
        var minVolumeValue = SettingProperties.getMinVolumeValue()!!.toDouble()
        val show = symbolList.filter { symbolInfo ->
            if (symbolInfo.market != getMarketName()) {
                return@filter false
            }
            if ((symbolInfo.volume / Constants.SYMBOL_VOLUME_UNIT) < minVolumeValue) {
                return@filter false
            }
            if (keyword != null && (!symbolInfo.currency.contains(keyword!!) && !symbolInfo.transCurrency.contains(
                    keyword!!
                ))
            ) {
                return@filter false
            }
            if (filterFavorite) {
                return@filter symbolInfo.isFavorite
            }
            if (filterAnalysis) {
                return@filter symbolInfo.isAnalysis
            }
            symbolInfo.volumeLevel == topTabContainer.selectedPosition
        }

        var realTimeCount = 0

        for (symbolInfo in show) {
            if (filterFavorite && symbolInfo.realtimePrimary) {
                realTimeCount++
            } else if (filterAnalysis && symbolInfo.realtimePrimary) {
                realTimeCount++
            } else if (symbolInfo.realtimePrimary
                && symbolInfo.volumeLevel == topTabContainer.selectedPosition
                && symbolInfo.market == getMarketName()
            ) {
                realTimeCount++
            }
        }
        tvRelaTimeCount.text = realTimeCount.toString() + "/" + realTimeAllCount.toString()
        try {
            if (TokenStorageUtil.read() != null) {
                symbolAdapter.update(show.sortedWith(ComparableHelper()))
            } else {
                symbolAdapter.update(null)
            }

        } catch (e: Exception) {
            logger.e("排序错误---->", e)
            logger.d("showList: $show ")
        }
    }

    private fun getMarketName(): String {
        return when (type) {
            1 -> "okex"
            2 -> "bian"
            3 -> "58coin"
            else -> "huobi"
        }
    }

    override fun onNetworkUnavailable() {

    }

    override fun select() {
        super.select()
        isSelected = true
        startAnimator()
    }

    override fun unSelect() {
        super.unSelect()
        isSelected = false
        stopAnimationIfNeed()
    }

    override fun onResume() {
        super.onResume()
        if (isSelected) {
            startAnimator()
        }
    }

    override fun onPause() {
        super.onPause()
        stopAnimationIfNeed()
    }

    private fun startAnimator() {
        if (!hadInjected) {
            return
        }
        stopAnimationIfNeed()
        animator = ValueAnimator.ofInt(0, 1, 0)
        with(animator!!) {
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            interpolator = LinearInterpolator()
            duration = 500
            addUpdateListener { animation ->
                if (recyclerView?.scrollState == 0) {
                    symbolAdapter.setTwinkling(animation.animatedValue == 0)
                }
            }
            start()
        }
    }

    private fun stopAnimationIfNeed() {
        animator?.run {
            removeAllUpdateListeners()
            end()
            cancel()
        }
        animator = null
    }

    companion object {
        const val HUOBI = 0
        const val OKEX = 1
        const val BIAN = 2
        const val COIN_58 = 3
        const val ME = 4
        const val DEFAULT_POSITION = 1
        private const val KEY_TYPE = "_KEY_TYPE_"
        fun newInstance(type: Int): SymbolFragment {
            return SymbolFragment().apply {
                arguments = Bundle().let {
                    it.putInt(KEY_TYPE, type)
                    it
                }
            }
        }
    }
}